package com.yzs.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzs.common.bean.R;
import com.yzs.entity.Notice;
import com.yzs.entity.PageResult;
import com.yzs.mapper.NoticeMapper;
import com.yzs.service.INoticeService;
import com.yzs.utils.JwtUtil;
import com.yzs.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NoticeServiceImpl implements INoticeService {
    @Autowired
    NoticeMapper mapper;
    @Autowired
    JwtUtil JwtUtil;
    @Override
    public R getNoticeByPage(Integer currentPage, Integer pageSize) {
        Page<Notice> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Notice> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("id");
        page = mapper.selectPage(page, wrapper);
        if (page.getRecords().isEmpty()) {
            return R.error("no data！");
        }
        PageResult<Notice> data = new PageResult<>(page.getTotal(), page.getRecords());
        return R.ok(data);
    }

    @Override
    public R updateNotice(Notice notice) {
        int i = mapper.updateById(notice);
        if (i == 1){
            return R.ok("更新成功！");
        }
        return R.error("更新失败！");
    }

    @Override
    public R addNotice(Notice notice,String token) {
        Integer id = JwtUtil.verifyToken(token);
        if(id == -1){
            return R.error("用户登录信息有误，请重新登录！");
        }
        notice.setTime(TimeUtil.getNowTime());
        notice.setPublisher(id);
        int i = mapper.insert(notice);
        if (i != 1){
            return R.error("新增公告失败！");
        }
        return R.ok("新增公告成功！",notice);
    }

    @Override
    public R deleteNotice(Integer id) {
        int i = mapper.deleteById(id);
        if (i == 1) {
            // 删除成功
            return R.ok("删除成功！");
        } else {
            return R.error("删除失败！");
        }
    }
}
